Best Time to Buy and Sell Stock
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
题目大意:给定一个数组,代表股票每天的价格,假设至多只能买卖一次,找出最大利润
题目难度:Easy
/**
* Created by gzdaijie on 16/6/11
* 每次更新最低价格 min,之后用 prices[i] - min 更新 result
* 实质是寻找满足i > j的 prices[i] - prices[j] 的最大值
*/
public class Solution {
public int maxProfit(int[] prices) {
if (prices == null || prices.length < 2) return 0;
int len = prices.length;
int min = prices[0];
int result = 0;
for (int i = 1; i < len; i++) {
if (prices[i] <= min) min = prices[i];
else result = Math.max(result, prices[i] - min);
}
return result;
}
}